package fun.zhufn.oldcomm;

import fun.zhufn.oldcomm.model.dao.GlobalDataDao;
import fun.zhufn.oldcomm.model.bo.json.JsonMap;
import fun.zhufn.oldcomm.model.bo.json.MyJsonParser;
import fun.zhufn.oldcomm.view.Login;

import javax.swing.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.logging.Logger;

/**
 * 入口类
 */
public class Main {
    private static final Logger log = Logger.getLogger(Main.class.toString());

    /**
     * @param args 入口点
     */
    public static void main(String []args) {
        try {
            String lookAndFeel = UIManager.getCrossPlatformLookAndFeelClassName();
            UIManager.setLookAndFeel(lookAndFeel);
        } catch (Exception e) {
            log.warning("设置主题失败！" + e);
        }

        File cf = new File("save.json");
        if (!cf.exists()) {
            log.info("创建配置文件中");
            FileOutputStream fs = null;
            try {
                cf.createNewFile();
                fs = new FileOutputStream(cf);
                fs.write("{}".getBytes());
                fs.close();
            } catch (Exception e) {
                log.warning("创建失败！" + e);
                return;
            } finally {
                if (fs != null) try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

        String data;
        FileInputStream fs = null;
        try {
            log.info("读取配置！");
            fs = new FileInputStream(cf);
            data = new String(fs.readAllBytes());
        } catch (Exception e) {
            log.warning("读取配置失败！" + e);
            return;
        } finally {
            try {
                if (fs != null) fs.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        try {
            GlobalDataDao.getInstance().loadData((JsonMap) MyJsonParser.parse(data));
            new Login().start();
        } catch (Exception e) {
            log.warning(e.toString());
        }
    }
}
